import React from 'react'
import {connect,} from 'react-redux'
import WechatModel from "../../model/Wechat";
import {withRouter} from 'react-router-dom'


// layouts
import CustomButton from "../../shared-components/CustomButton/CustomBotton"

// antd-mobile
import {NavBar, Icon, WingBlank, WhiteSpace,} from 'antd-mobile'

// constants
import constants, {local, test} from "../../utils/constants"
import CreditCard from "../../shared-components/CreditCard/CreditCard"

// icon
import DetailIcon from '../../res/images/web/wallet/info@2x.png'
import WeChatIcon from '../../res/images/web/wallet/wechat 2@2x.png'
import CheckIcon from '../../res/images/web/wallet/choose pay-selected@2x.png'
import UnCheckIcon from '../../res/images/web/wallet/choose@2x.png'
import CancelIcon from '../../res/images/web/wallet/cancel@2x.png'

// mock data
import {mockCreditList} from '../../utils/mockdata'

// utils
import {onSelected} from "../../utils/commonfunc"
import './wallet.css'
import LocalStorageService from "../../utils/LocalStorageService";
import {Modal} from "antd-mobile";
import {goBack} from "../../utils/goback";
import {onTaskDone} from "../plan-detail/plan-detail";
import TaskDoneNotice from "../plan-detail/task-done-notice/task-done-notice";
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";

class WalletContainer extends React.Component {

    constructor(props) {
        super(props)
        this.wechat = new WechatModel()
        this.uid = LocalStorageService.get('userid')
        this.state = {
            modal: {
                pay: false,
                order: false,
            },
            creditList: mockCreditList,
            payList: [
                {title: '微信(默认)', icon: WeChatIcon, select: true,},
            ],
            goBack: '',
            taskDone: false,
            taskInfo: '',
        }
    }

    componentDidMount() {

        const userDetail = this.props.user.userdetail
        const uid = LocalStorageService.get('userid')
        this.props.fetchUserDetail({uid,})
        const login = LocalStorageService.get('isLogin')
        if (login) {
            this.checkWechatOrder()
        }
    }

    checkWechatOrder = () => {
        const search = this.props.location.search
        if (search === '') return
        let obj = {}
        search
            .slice(1)
            .split('&')
            .map(kv => {
                const arr = kv.split('=')
                const key = arr[0]
                const val = arr[1]
                obj[key] = val
            })
        const goBack = obj.goback
        const dealno = obj.dealno
        const style = Number(obj.style)
        // const list = search.split('?').slice(1)
        // const dealno = list[0].split('=')[1]
        // const goBack = list[1].split('=')[1]
        this.setState({
            goBack,
        })
        // const wxdealno = list[1].split('=')[1]
        const btnList = [
            { text: <span style={{color: constants.themeColor}}>已完成支付</span>, onPress: () => this.comfirmWechatOrder({dealno, style,})},
            { text: <span style={{color: 'rgba(51,51,51,0.3)'}}>支付遇到问题, 重新支付</span>, onPress: () => {} },
            // {}
        ]
        Modal.alert('请确认微信支付是否完成', '', btnList)
        // this.props.doCheckWechatOrder({
        //     dealno,
        //     wxdealno,
        // })
    }

    comfirmWechatOrder = (params) => {
        this.props.doCheckWechatOrder(params)
        onTaskDone(this.uid, 'czjb')
            .then(data => {
                if (data.Code === 0) {
                    this.setState({
                        taskDone: true,
                        taskInfo: data.Msg,
                    })
                }
            })
    }

    handleCreditClick = (e, credit) => {
        const creditList = this.state.creditList
        const callback = (list) => {
            this.setState({
                creditList: list
            })
        }
        onSelected(credit, creditList, 'coins', 'active', callback)
    }

    handlePayItemClick = (pay) => {
        const payList = this.state.payList
        const callback = (list) => {
            this.setState({
                payList: list
            })
        }
        onSelected(pay, payList, 'title', 'select', callback)
    }

    cancel = (key) => {
        this.setState({
            modal: {
                [key]: false,
            }
        })
    }

    showModal = (key) => {
        this.setState({
            modal: {
                [key]: true,
            },
        })
    }

    wechatPay = () => {
        const i = this.state.creditList.findIndex(c => c.active === true)
        const style = i + 1
        const uid = LocalStorageService.get('userid')
        let baseUrl
        if (test) {
            if (local) {
                baseUrl = 'http://localhost:3001/wallet?'
            } else {
                baseUrl = 'http://123.207.85.242:8080/wallet?'
            }
        } else {
            baseUrl = 'http://www.youtoball.com:8080/wallet?'
        }
        // let baseUrl = test ? 'http://123.207.85.242:8080/wallet?' :
        let redirect = baseUrl + 'goback=' + '&style=' + style
        // const location = ''
        this.props.doWechatPay({
            uid,
            style,
            redirect,
            // location,
        })
    }

    render() {

        const history = this.props.history
        const creditList = this.state.creditList
        const handleCreditClick = this.handleCreditClick
        const userDetail = this.props.user.userdetail
        const {
            Gold,
        } = userDetail

        const leftContent = (
            <>
                <Icon type='left' size='lg'/>
                <span className='go-back-layout-icon-title go-back-layout-icon-title-white'>我的钱包</span>
            </>

        )

        const rightContent = (
            <div onClick={() => history.push('consume')}>
                <span style={{opacity: '0.8', paddingRight: '3px'}}>资金明细</span>
                <img src={DetailIcon} alt='' style={{width: 10, height: 10,}}/>
            </div>
        )

        const creditListTemplate = (creditList.map((credit) => {
            return (
                <CreditCard
                    key={credit.price}
                    credit={credit}
                    onClick={(e) => {handleCreditClick(e, credit)}}
                />
            )
        }))

        const coin = (
            <div className='wallet-coin-ctn'>
                <p className='wallet-coin'>{Gold}</p>
                <p className='wallet-coin-text'>金币数量</p>
                {/*<p className='wallet-coin-text wallet-coin-add'>充值的金币不能用于提现</p>*/}
            </div>
        )

        const credits = (
            <WingBlank>
                <div className='wallet-card-ctn'>
                    <WingBlank>
                        <p className='wallet-card-title'>充值数量</p>
                        <div className='flex-space-between-align-center flex-wrap-container'>
                            {creditListTemplate}
                        </div>
                    </WingBlank>
                </div>
            </WingBlank>
        )

        const info = (
            <WingBlank>
                <ul className='wallet-ul'>
                    <li>1. 充值即代表阅读并已同意<a
                        style={{color: '#008CFF'}}
                        onClick={() => {this.props.history.push('./deposit-policy')}}
                    >《充值服务协议》</a></li>
                    <li>2. 充值金币即赠送相关经验值，可提升等级身份</li>
                    <li>3. 充值成功后，有可能会延迟显示，需要缓冲时间，请耐心等待</li>
                    <li>4. 如充值始终无法到账，可联系QQ：2484275675</li>
                </ul>
            </WingBlank>
        )

        const btn = (
            <WingBlank>
                <CustomButton
                    inline='true'
                    shadow='0px 6px 8px 0px rgba(33,58,75,0.2)'
                    onClick={() => this.showModal('pay')}
                >确认充值</CustomButton>
            </WingBlank>
        )

        const select = creditList.find(c => c.active === true)

        const payList = this.state.payList.map((pay, i) => (
            <div
                key={i}
                className={`flex-space-between-align-center pay-list-item${pay.select ? ' pay-list-item-select' : ''}`}
                onClick={(e) =>this.handlePayItemClick(pay)}
            >
                <div className='flex-center-align-center'>
                    <img src={pay.icon} alt='' style={{marginRight: '8px', height: 28, width: 28,}}/>
                    <span>微信</span>
                </div>

                <div className='flex-center-align-center'>
                    <img alt='' style={{height: 24, width: 24,}} src={pay.select ? CheckIcon : UnCheckIcon}/>
                </div>
            </div>

        ))

        const {
            price,
        } = select

        const modalBtn = <CustomButton
                shadow='0px 6px 10px 0px rgba(33,58,75,0.4)'
                onClick={() => this.wechatPay()}
            ><span style={{letterSpacing: '12px'}}>确认支付</span></CustomButton>

        const payModal = <Modal
            popup
            visible={this.state.modal.pay}
            onClose={() => this.cancel('pay')}
            animationType="slide-up"
        >
            <div style={{position: 'relative', padding: '15px'}}>

                <img alt='' src={CancelIcon} onClick={this.cancel} className='modal-cancel-icon'/>

                <div className='wallet-modal'>
                    <p className='wallet-modal-title'>支付详情</p>
                    <p className='wallet-modal-price'>
                        <span className='wallet-modal-price-rmb'>¥ </span>
                        {price}
                    </p>
                </div>
                <div style={{textAlign: 'left', marginBottom: '6px'}}>
                    <span className='pay-list-title'>支付方式</span>
                    {payList}
                </div>


                {modalBtn}

            </div>

        </Modal>

        const goBackUrl = this.state.goBack === '' ? './' : this.state.goBack
        return (
            <>
                {this.state.taskDone && <TaskDoneNotice taskInfo={this.state.taskInfo} onCancel={() => this.setState({taskDone: false,})}/>}
                {payModal}
                {/*{orderModal}*/}
                <NavBar
                    leftContent={leftContent}
                    onLeftClick={() => {goBack(history, goBackUrl)}}
                    style={{backgroundColor: `${constants.themeColor}`}}
                    rightContent={rightContent}
                />
                {coin}
                {credits}
                <WhiteSpace/>
                {info}
                <WhiteSpace/>
                <div className='mg-b-2'>
                    {btn}
                </div>
            </>
        )

        // return super.render();
    }


}

// const WalletContainer = props => {
//
//     const [creditList, setCreditList] = useState(mockCreditList)
//
//     const handleCreditClick = (e, credit) => {
//         onSelected(credit, creditList, 'coins', 'active', setCreditList)
//     }
//
//     const {history} = props
//
//     const leftContent = (
//         <>
//             <Icon type='left' size='lg'/>
//             <span className='go-back-layout-icon-title go-back-layout-icon-title-white'>我的钱包</span>
//         </>
//
//     )
//
//     const rightContent = (
//         <div onClick={() => history.push('consume')}>
//             <span style={{opacity: '0.8', paddingRight: '3px'}}>资金明细</span>
//             <img src={DetailIcon} alt=''/>
//         </div>
//     )
//
//     const creditListTemplate = (creditList.map((credit) => {
//         return (
//             <CreditCard
//                 key={credit.price}
//                 credit={credit}
//                 onClick={(e) => {handleCreditClick(e, credit)}}
//             />
//         )
//     }))
//
//     const coin = (
//         <div className='wallet-coin-ctn'>
//             <p className='wallet-coin'>0.00</p>
//             <p className='wallet-coin-text'>金币数量</p>
//             <p className='wallet-coin-text wallet-coin-add'>充值的金币不能用于提现</p>
//         </div>
//     )
//
//     const credits = (
//         <WingBlank>
//             <div className='wallet-card-ctn'>
//                 <WingBlank>
//                     <p className='wallet-card-title'>充值数量</p>
//                     <div className='flex-space-between-align-center flex-wrap-container'>
//                         {creditListTemplate}
//                     </div>
//                 </WingBlank>
//             </div>
//         </WingBlank>
//     )
//
//     const info = (
//         <WingBlank>
//             <ul className='wallet-ul'>
//                 <li>1. 充值即代表阅读并已同意<a href='#' style={{color: '#008CFF'}}>《充值服务协议》</a></li>
//                 <li>2. 充值金币即赠送相关经验值，可提升等级身份</li>
//                 <li>3. 充值成功后，有可能会延迟显示，需要缓冲时间，请耐心等待</li>
//                 <li>4. 如充值始终无法到账，可联系QQ：123456</li>
//             </ul>
//         </WingBlank>
//     )
//
//     const btn = (
//         <WingBlank>
//             <CustomButton
//                 inline='true'
//                 shadow='0px 6px 8px 0px rgba(43,138,247,0.2)'
//             >确认充值</CustomButton>
//         </WingBlank>
//     )
//
//     return (
//         <>
//             <NavBar
//                 leftContent={leftContent}
//                 onLeftClick={() => {history.goBack()}}
//                 style={{backgroundColor: `${constants.themeColor}`}}
//                 rightContent={rightContent}
//             />
//             {coin}
//             {credits}
//             <WhiteSpace/>
//             {info}
//             <WhiteSpace/>
//             <div className='mg-b-2'>
//                 {btn}
//             </div>
//         </>
//     )
// }

const mapState = (state) => ({
    user: state.user,
})

const mapDispatchToProps = ({user: {fetchUserDetail, doWechatPay, doCheckWechatOrder},}) => ({
    fetchUserDetail: (id) => fetchUserDetail(id),
    doWechatPay: (payload) => doWechatPay(payload),
    doCheckWechatOrder: (payload) => doCheckWechatOrder(payload)
})

export default connect(mapState, mapDispatchToProps)(withRouter(WalletContainer))
